package com.hxzy.projectssmplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.projectssmplus.dto.SysRoleDTO;
import com.hxzy.projectssmplus.entity.SysAdminUser;
import com.hxzy.projectssmplus.entity.SysAdminUserRole;
import com.hxzy.projectssmplus.entity.SysRole;
import com.hxzy.projectssmplus.entity.SysRoleMenu;
import com.hxzy.projectssmplus.mapper.SysAdminUserRoleMapper;
import com.hxzy.projectssmplus.mapper.SysRoleMapper;
import com.hxzy.projectssmplus.mapper.SysRoleMenuMapper;
import com.hxzy.projectssmplus.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {



    @Override
    public IPage<SysRole> search(IPage ipage, SysRoleDTO sysRoleDTO) {
        QueryWrapper<SysRole> queryWrapper=new QueryWrapper();
        if(StringUtils.isNotBlank( sysRoleDTO.getName())){
            queryWrapper.like("name",  sysRoleDTO.getName());
        }

        if(StringUtils.isNotBlank( sysRoleDTO.getPerms())){
            queryWrapper.like("perms",  sysRoleDTO.getPerms());
        }

        if( sysRoleDTO.getStatus()!=null){
            queryWrapper.eq("status", sysRoleDTO.getStatus());
        }
         //日期范围
        if(sysRoleDTO.getMap().size()==2){
            //DATE_FORMAT(create_time,'%Y%m%d')
            String beginStr="DATE_FORMAT('"+sysRoleDTO.getMap().get("begin")+"','%Y%m%d')";
            String endStr="DATE_FORMAT('"+sysRoleDTO.getMap().get("end")+"','%Y%m%d')";
            //queryWrapper.between("DATE_FORMAT(create_time,'%Y%m%d')",  beginStr, endStr);
            //有sql注入风险
            queryWrapper.apply("date_format(create_time,'%Y%m%d') between   "+beginStr+"    and "+endStr);

        }

        IPage<SysRole> page =  super.page(ipage, queryWrapper);

        return page;
    }

    @Autowired
    private SysRoleMapper  sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysAdminUserRoleMapper sysAdminUserRoleMapper;

    /**
     *
     * 条件查询
     * @param ipage
     * @param sysRoleDTO
     * @return
     */
    @Override
    public IPage<SysRole> searchByXML(IPage ipage, SysRoleDTO sysRoleDTO) {
        List<SysRole> sysRoleList=sysRoleMapper.searchByXML(ipage,sysRoleDTO);
        //满足条件集合，自已手动加入到ipage类中去
        ipage.setRecords(sysRoleList);

        return ipage;
    }

    /**
     * 根据用户id查询它拥有的角色 perms这一列(多表联接，还是使用最原始的mybatis)
     * @param adminUserId
     * @return
     */
    @Override
    public Set<String> ownerRoleByUserId(Integer adminUserId) {
        return this.sysRoleMapper.ownerRoleByUserId(adminUserId);

    }

    /**
     * 修改数据权限信息
     * @param role 角色信息
     * @return
     */
    @Override
    public int authDataScope(SysRole role) {
        super.updateById(role);

        this.sysRoleMenuMapper.deleteRoleMenuByRoleId(role.getId());

        return insertRoleMenu(role);
    }

    /**
     * 批量取消授权用户角色
     * @param roleId 角色ID
     * @param userIds 需要取消授权的用户数据ID
     * @return
     */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds) {
        return this.sysAdminUserRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    /**
     * 批量选择授权用户角色
     * @param roleId 角色ID
     * @param userIds 需要删除的用户数据ID
     * @return
     */
    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds) {
        List<SysAdminUserRole> list = new ArrayList<>();
        for (Long userId : userIds) {
            SysAdminUserRole ur = new SysAdminUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }

        return sysAdminUserRoleMapper.batchUserRole(list);
    }

    /**
     * 根据用户ID查询角色
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<SysRole> selectRolesByUserId(Long userId) {
        List<SysRole> userRoles = this.sysRoleMapper.selectRolePermissionByUserId(userId);

        List<SysRole> roles = this.sysRoleMapper.selectRoleAll();

        for (SysRole role : roles) {
            for (SysRole userRole : userRoles) {
                if (role.getId().longValue() == userRole.getId().longValue()) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 根据角色id查询角色详细信息
     * @param roleId 角色ID
     * @return
     */
    @Override
    public SysRole selectRoleById(Long roleId) {
        return this.sysRoleMapper.selectRoleById(roleId);
    }

    /**
     * 新增保存角色信息
     * @param role 角色信息
     * @return
     */
    @Override
    public int insertRole(SysRole role) {
        role.setCreateTime(new Date());
        role.setCreateBy("admin");
        this.sysRoleMapper.insertRole(role);
        return insertRoleMenu(role);
    }

    /**
     * 通过角色id删除角色
     * @param roleId 角色ID
     * @return
     */
    @Override
    public int deleteRoleById(Long roleId) {
        this.sysRoleMenuMapper.deleteRoleMenuByRoleId(roleId);

        return this.sysRoleMapper.deleteRoleById(roleId);
    }

    /**
     * 取消授权用户角色
     * @param userRole 用户和角色关联信息
     * @return
     */
    @Override
    public int deleteAuthUser(SysAdminUserRole userRole) {
        return this.sysAdminUserRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds())
        {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = sysRoleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }


}
